const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jwt = require('koa-jwt')
const cors = require('./middleware/cors')

const { JWT_SECRET, JWT_IGNORE_PATH } = require('./config/constant')
const customError = require('./middleware/customError')

const index = require('./routes/index')
const users = require('./routes/users')
const works = require('./routes/works')
const templates = require('./routes/templates')
const channels = require('./routes/channels')
const utils = require('./routes/utils')

// 用于cookie签名
app.keys = ['SHjUcKJS9TqcPWGk']

// error handler
onerror(app)

// 支持跨域
app.use(cors)

// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text']
  })
)
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(
  views(__dirname + '/views', {
    extension: 'pug'
  })
)

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 自定义捕获错误 如：401
app.use(customError)
app.use(
  jwt({
    secret: JWT_SECRET,
    cookie: 'jwt_token' // 使用 cookie 存储 token
  }).unless({
    // 定义哪些路由忽略 jwt 验证
    path: JWT_IGNORE_PATH
  })
)

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(works.routes(), works.allowedMethods())
app.use(templates.routes(), templates.allowedMethods())
app.use(channels.routes(), channels.allowedMethods())
app.use(utils.routes(), utils.allowedMethods())

// 全局监听异常信息
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
